package com.sinog.biz.service.business.impl;

import com.sinog.biz.BizApplication;
import com.sinog.biz.service.business.XtglCensusService;
import com.sinog.core.util.JsonUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc sfbadmin账号---系统管理---统计---统计省份与司法部对应表之间的数量关系
 * @author 潘志成
 * @date 2022/8/15 15:46
 */
@Service
public class XtglCensusServiceImpl implements XtglCensusService {

    private JdbcTemplate buTemplate;

    @Override
    public String censusAll() {
        ApplicationContext applicationContext = BizApplication.applicationContext;
        //获取部级数据源
        buTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        //按省份分类
        String selectGroupSql = "SELECT proId,proName ,COUNT(1) FROM tbsys_count GROUP BY proId ";
        //查询全部数据
        String selectAllSql = "SELECT * FROM tbsys_count";
        List<Map<String,Object>> group = buTemplate.queryForList(selectGroupSql);
        List<Map<String,Object>> all = buTemplate.queryForList(selectAllSql);
        //142	41	河南省	prisoner_zn	32419	32012   ------------表中数据格式
        List<Map<String,String>> arrayList = new ArrayList<>();
        for(Map<String,Object> map : all) {
            Map<String,String> m1 = new HashMap<>(16);
            StringBuilder sb = new StringBuilder();
            //省份名称
            String proName = (String)map.get("proName");
            //key---表名作为key
            String tableName = (String)map.get("tableName");
            //value---统计数量拼接信息作为value
            Integer proCount = (Integer)map.get("proCount");
            Integer buCount = (Integer)map.get("buCount");
            boolean flag = proCount - buCount > 0;
            sb.append("【").append(proCount).append("】/【").append(buCount).append("】/【")
              .append(flag ? proCount - buCount : buCount - proCount).append("】");
            m1.put(tableName,sb.toString());
            //每张表携带省份信息
            m1.put("childs",proName);
            //将信息处理好的表放入list集合中，准备进行下一步的处理
            arrayList.add(m1);
        }
        List<Map<String,String>> list = new ArrayList<>();
        for(Map<String,Object> map : group) {
            //每个map是每个省份
            String proName = (String)map.get("proName");
            String proId = (String)map.get("proId");
            Map<String,String> proMap = new HashMap<>(16);
            proMap.put(proId,proName);
            list.add(proMap);
        }
        for(Map<String,String> map : arrayList) {
            for(Map<String,String> proMap : list) {
                if(proMap.containsValue(map.get("childs"))) {
                    proMap.putAll(map);
                }
            }
        }
        return JsonUtil.toText(all.size(),list);
    }
}